//
//  UIImage+GQ.m
//  DoubleLineTracking
//
//  Created by guiqing on 12/6/14.
//  Copyright (c) 2014 guiqing. All rights reserved.
//

#import "UIImage+GUI.h"
#import <QuartzCore/QuartzCore.h>
#import <Accelerate/Accelerate.h>

@implementation UIImage (GUI)


+(UIImage *)imageAdjustedWithName:(NSString *)name
{
//    if(NO){
//        
//        NSString * newName = [name stringByAppendingString:@"_os7"];
//    
//        UIImage *image = [UIImage imageNamed:newName];
//        
//        if (nil==image) {
//            
//            image= [UIImage imageNamed:name];
//            
//        }
//        
//        return image;
//    }
//    
    //not iOS7
    return [UIImage imageNamed:name];
    

}



+ (UIImage *)imageResizeWithName:(NSString *)name
{
    
    UIImage *image = [self imageNamed:name];
    //拉伸中间一点
    return [image stretchableImageWithLeftCapWidth:image.size.width*0.5 topCapHeight:image.size.height*0.5];

}


+ (UIImage *)imageResizedImageWithName:(NSString *)name left:(CGFloat)left top:(CGFloat)top
{
    UIImage *image = [self imageNamed:name];
    return [image stretchableImageWithLeftCapWidth:image.size.width * left topCapHeight:image.size.height * top];
}

+ (UIImage *)imageWithColor:(UIColor *)color
{
  return  [self imageWithColor:color size:CGSizeMake(100, 100)];
}

+ (UIImage*)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGFloat imageW = size.width;
    CGFloat imageH = size.height;
    // 1.开启基于位图的图形上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageW, imageH), NO, 0.0);
    
    // 2.画一个color颜色的矩形框
    [color set]; //set 是同时设置描边和填充的颜色 ,而 setFill只设置填充色
    UIRectFill(CGRectMake(0, 0, imageW, imageH));
    
    // 3.拿到图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 4.关闭上下文
    UIGraphicsEndImageContext();
    
    return image;

}

/**
 *  生成头像(使用图像文件名)
 *
 *  @param icon   头像图片名称
 *  @param border 头像边框大小
 *  @param color  头像边框的颜色
 *
 *  @return 生成好的头像
 */
+ (instancetype)roundCornerImageWithName:(NSString *)iconString border:(NSInteger)border color:(UIColor *)color
{
    // 0. 加载原有图片
    UIImage *image = [UIImage imageNamed:iconString];
    
    // 1.创建图片上下文
    CGFloat margin = border;
    CGSize size = CGSizeMake(image.size.width + margin, image.size.height + margin);
    
    // YES 不透明 NO 透明
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    // 2.绘制大圆
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, size.width, size.height));
    [color set];
    CGContextFillPath(ctx);
    
    // 3.绘制小圆
    CGFloat smallX = margin * 0.5;
    CGFloat smallY = margin * 0.5;
    CGFloat smallW = image.size.width;
    CGFloat smallH = image.size.height;
    CGContextAddEllipseInRect(ctx, CGRectMake(smallX, smallY, smallW, smallH));
    //    [[UIColor greenColor] set];
    //    CGContextFillPath(ctx);
    // 4.指点可用范围, 可用范围的适用范围是在指定之后,也就说在在指定剪切的范围之前绘制的东西不受影响
    CGContextClip(ctx);
    
    // 5.绘图图片
    [image drawInRect:CGRectMake(smallX, smallY, smallW, smallH)];
    
    // 6.取出图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    return newImage;
    
}

/**
 *  生成头像(使用UIImage)
 *
 *  @param icon   头像图片名称
 *  @param border 头像边框大小
 *  @param color  头像边框的颜色
 *
 *  @return 生成好的头像
 */
+ (instancetype)roundCornerImageWithImage:(UIImage *)icon border:(NSInteger)border color:(UIColor *)color
{
    // 0. 加载原有图片
    UIImage *image = icon;
    
    // 1.创建图片上下文
    CGFloat margin = border;
    CGSize size = CGSizeMake(image.size.width + margin, image.size.height + margin);
    
    // YES 不透明 NO 透明
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    // 2.绘制大圆
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, size.width, size.height));
    [color set];
    CGContextFillPath(ctx);
    
    // 3.绘制小圆
    CGFloat smallX = margin * 0.5;
    CGFloat smallY = margin * 0.5;
    CGFloat smallW = image.size.width;
    CGFloat smallH = image.size.height;
    CGContextAddEllipseInRect(ctx, CGRectMake(smallX, smallY, smallW, smallH));
    //    [[UIColor greenColor] set];
    //    CGContextFillPath(ctx);
    // 4.指点可用范围, 可用范围的适用范围是在指定之后,也就说在在指定剪切的范围之前绘制的东西不受影响
    CGContextClip(ctx);
    
    // 5.绘图图片
    [image drawInRect:CGRectMake(smallX, smallY, smallW, smallH)];
    
    // 6.取出图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    return newImage;
    
}

+(instancetype)imageWithRect:(CGRect)rect imageName:(NSString*)imgStr
{
    UIImage* image = [UIImage imageNamed:imgStr];
    
    //根据矩形创建一个基于位图的图形上下文
    UIGraphicsBeginImageContext(rect.size);
    //获取当前 quartz2d 绘图环境
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    //坐标系转换
    CGContextRotateCTM(currentContext, M_PI);
    CGContextTranslateCTM(currentContext, -rect.size.width, -rect.size.height);
    
    
    //设置当前绘图环境到矩形框
    CGContextClipToRect(currentContext, rect);
    //绘图
    CGContextDrawImage(currentContext, rect, image.CGImage);
    //获得图片
    UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
    //删除位图上下文
    UIGraphicsEndImageContext();
    
    return cropped;

}



- (UIImage *)glassImage
{
    return [self glassImageWithLevel:1.0];
}


- (UIImage *)glassImageWithLevel:(CGFloat)level
{
    //if the level is illegal, set it to be default value (0.5)
    if (level < 0.f || level > 1.f) {
        level = 0.5f;
    }
    
    //
    int boxSize = (int)(level * 80);
    boxSize = boxSize - boxSize % 2 + 1;
    
    CGImageRef img = self.CGImage;
    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;
    void *pixelBuffer;
    
    //create vImage_Buffer with data from CGImageRef
    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    
    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    
    //create vImage_Buffer for output
    pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
    
    if(pixelBuffer == NULL)
        NSLog(@"No pixelbuffer");
    
    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    // Create a third buffer for intermediate processing
    void *pixelBuffer2 = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
    vImage_Buffer outBuffer2;
    outBuffer2.data = pixelBuffer2;
    outBuffer2.width = CGImageGetWidth(img);
    outBuffer2.height = CGImageGetHeight(img);
    outBuffer2.rowBytes = CGImageGetBytesPerRow(img);
    
    //perform convolution
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer2, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    error = vImageBoxConvolve_ARGB8888(&outBuffer2, &inBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(outBuffer.data,
                                             outBuffer.width,
                                             outBuffer.height,
                                             8,
                                             outBuffer.rowBytes,
                                             colorSpace,
                                             kCGImageAlphaNoneSkipLast);
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    
    //clean up
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    
    free(pixelBuffer);
    free(pixelBuffer2);
    
    CFRelease(inBitmapData);
    
    CGImageRelease(imageRef);
    
    
    return returnImage;
}



+(instancetype)roundRectImageWithRGBColor:(UIColor*)color
{
//    UIImage *image =  [UIImage imageWithColor:kcLightGreen];
//    // 0. 加载原有图片
//    //UIImage *image = [UIImage imageNamed:icon];
//    
//    // 1.创建图片上下文
//    CGSize size = CGSizeMake(300, 300);
//    // YES 不透明 NO 透明
//    UIGraphicsBeginImageContextWithOptions(size,YES, 0);
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    
//    float fw = 180;
//    float fh = 280;
//    
//    CGContextMoveToPoint(context, fw, fh-20);  // 开始坐标右边开始
//    CGContextAddArcToPoint(context, fw, fh, fw-20, fh, 10);  // 右下角角度
//    CGContextAddArcToPoint(context, 120, fh, 120, fh-20, 10); // 左下角角度
//    CGContextAddArcToPoint(context, 120, 250, fw-20, 250, 10); // 左上角
//    CGContextAddArcToPoint(context, fw, 250, fw, fh-20, 10); // 右上角
//    CGContextClosePath(context);
//    CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径
//    
//    // 4.指点可用范围, 可用范围的适用范围是在指定之后,也就说在在指定剪切的范围之前绘制的东西不受影响
//    CGContextClip(context);
//    // 5.绘图图片
//    [image drawInRect:CGRectMake(0,0, fw, fh)];
//    // 6.取出图片
//    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    return image;
    
    // 0. 加载原有图片
    UIImage *image = [UIImage imageWithColor:[UIColor colorWithRed:108 green:185 blue:166 alpha:1]];
    // 1.创建图片上下文
    CGSize size = CGSizeMake(300,300);
    
    // YES 不透明 NO 透明
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    // 2.拿到当前图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    //3. 绘制矩形
//    CGRect rrect = CGRectMake(0, 0,200.0, 100.0);
//    CGFloat radius = 3.0;
//    CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect);
//    CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect);
//    CGContextMoveToPoint(ctx, minx, midy);
//    // Add an arc through 2 to 3
//    CGContextAddArcToPoint(ctx, minx, miny, midx, miny, radius);
//    // Add an arc through 4 to 5
//    CGContextAddArcToPoint(ctx, maxx, miny, maxx, midy, radius);
//    // Add an arc through 6 to 7
//    CGContextAddArcToPoint(ctx, maxx, maxy, midx, maxy, radius);
//    // Add an arc through 8 to 9
//    CGContextAddArcToPoint(ctx, minx, maxy, minx, midy, radius);
//    // Close the path
//    CGContextClosePath(ctx);
    // 不要 draw, draw 了就没有了
    //CGContextDrawPath(context, kCGPathFillStroke);
    
    float fw = 180;
    float fh = 280;
    
    CGContextMoveToPoint(ctx, fw, fh-20);  // 开始坐标右边开始
    CGContextAddArcToPoint(ctx, fw, fh, fw-20, fh, 10);  // 右下角角度
    CGContextAddArcToPoint(ctx, 120, fh, 120, fh-20, 10); // 左下角角度
    CGContextAddArcToPoint(ctx, 120, 250, fw-20, 250, 10); // 左上角
    CGContextAddArcToPoint(ctx, fw, 250, fw, fh-20, 10); // 右上角
    CGContextClosePath(ctx);
    
    // 4.指点可用范围, 可用范围的适用范围是在指定之后,也就说在在指定剪切的范围之前绘制的东西不受影响
    CGContextClip(ctx);
    
    // 5.绘图图片
    [image drawInRect:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    // 6.取出图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    return newImage;

}

/**
 *  缩放图片到指定的尺寸
 *  @param img  原始图片
 *  @param size 目标尺寸
 *
 *  @return 生成的图片
 */
+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

/**
 *  通过缩放图片和裁剪生成一张图片
 *  (以宽度和高度中小的一个作为依据)
 *  @param targetSize 目标尺寸
 *
 *  @return 生成的图片
 */
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


@end
